package edu.msg.jthr.backend.service.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * The password service's class
 * 
 * @author Adorjan
 * 
 */
public class PasswordService {

	private static final Logger LOG = LoggerFactory
			.getLogger(PasswordService.class);
	private static String PASSWORD_ENCODING = "utf-8";
	private static String PASSWORD_HASHING = "SHA";

	/**
	 * This method generates the password's hashed form
	 * 
	 * @param password
	 * @return hashed password
	 */
	public static String generateHashedPassword(final String password) {
		String hashedPassword = "";
		byte[] initialBytes;
		try {
			initialBytes = (password).getBytes(PASSWORD_ENCODING);
			final MessageDigest algorithm = MessageDigest
					.getInstance(PASSWORD_HASHING);
			algorithm.reset();
			algorithm.update(initialBytes);
			final byte[] hashedBytes = algorithm.digest();
			hashedPassword = new String(hashedBytes);
		} catch (final UnsupportedEncodingException nsae) {
			LOG.error("Password encryption failed: unsupported encoding", nsae);
		} catch (final NoSuchAlgorithmException ae) {
			LOG.error(
					"Password encryption failed: hashing algorithm not supported",
					ae);
		}
		return hashedPassword;
	}
}
